﻿using Microsoft.Win32;
using mshtml;
using SHDocVw;
using System;
using System.Runtime.InteropServices;

namespace Application.Presentation.Windows.IEHook
{
    public class IEBrowserHelperObject : IObjectWithSite
    {
        private WebBrowser browser;

        public int SetSite([MarshalAs(UnmanagedType.IUnknown)] object site)
        {
            if (site == null)
            {
                this.browser.DocumentComplete -= Browser_DocumentComplete;
                this.browser = null;
            }
            else
            {
                this.browser = (WebBrowser)site;
                this.browser.DocumentComplete += Browser_DocumentComplete;
            }

            return 0;
        }

        public int GetSite(ref Guid guid, out IntPtr site)
        {
            IntPtr punk = Marshal.GetIUnknownForObject(this.browser);
            int hr = Marshal.QueryInterface(punk, ref guid, out site);
            Marshal.Release(punk);

            return hr;
        }

        private void Browser_DocumentComplete(object pDisp, ref object URL)
        {
            //HTMLHeadElement
            var document = (HTMLDocument)this.browser.Document;

            document.body.innerHTML += "Hello World!";
            //document.getElementsByTagName("body");
        }

        #region Register
        public static string BHORegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects";

        [ComRegisterFunction]
        public static void RegisterBHO(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHORegistryKey, true);

            if (registryKey == null)
            {
                registryKey = Registry.LocalMachine.CreateSubKey(BHORegistryKey);
            }

            string guid = type.GUID.ToString("B");

            RegistryKey outKey = registryKey.OpenSubKey(guid);

            if (outKey == null)
            {
                outKey = registryKey.CreateSubKey(guid);
            }

            registryKey.Close();

            outKey.Close();
        }

        [ComUnregisterFunction]
        public static void UnregisterBHO(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHORegistryKey, true);
            string guid = type.GUID.ToString("B");
            if (registryKey != null)
            {
                registryKey.DeleteSubKey(guid, false);
            }
        } 
        #endregion
    }
}
